package com.wangmin.intercept;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.GeolocationPermissions;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.wangmin.intercept.bean.AdFilterBean;
import com.wangmin.intercept.bean.ProtocalMsg;
import com.wangmin.intercept.init.SdkInit;
import com.wangmin.intercept.listener.ToggledFullscreenCallback;
import com.wangmin.intercept.listener.UrlAddedListener;
import com.wangmin.intercept.listener.WebchromClientCallback;
import com.wangmin.intercept.manager.SystemBarTintManager;
import com.wangmin.intercept.service.SocketService;
import com.wangmin.intercept.utils.LogUtils;
import com.wangmin.intercept.utils.ViewUtils;
import com.wangmin.intercept.view.AudioAutoShowTitleFramLayout;
import com.wangmin.intercept.websetting.CustomWebChromeClient;
import com.wangmin.intercept.websetting.CustomWebViewClient;
import com.wangmin.intercept.websetting.CustomWebview;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;

public class MainActivity extends AppCompatActivity {
    @Bind(R.id.wv_content)
    CustomWebview wvContent;
    @Bind(R.id.pb_loading)
    ProgressBar pbLoading;
    @Bind(R.id.iv_error)
    ImageView ivError;
    @Bind(R.id.nonVideoLayout)
    FrameLayout nonVideoLayout;
    @Bind(R.id.videoLayout)
    RelativeLayout videoLayout;
    @Bind(R.id.iv_back)
    ImageView ivBack;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.rl_content_full)
    AudioAutoShowTitleFramLayout rlContentFull;
    @Bind(R.id.root)
    RelativeLayout root;
    @Bind(R.id.in_error)
    public View errorView;
    @Bind(R.id.in_loading)
    public View loadingView;
    @Bind(R.id.bt_error)
    public Button errorRefresh;
    private ProgressBar progressBar;
    private CustomWebChromeClient customWebChromeClient;
    private CustomWebViewClient customWebViewClient;
    private SystemBarTintManager tintManager;
    private CustomWebview webViewLoadBook;
    private FrameLayout frameLayout;
    private LogUtils logUtils;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        logUtils = LogUtils.getNewInstance("MainActivity");
        initWebview();
        wvContent.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_UP) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && wvContent.canGoBack()) {
                        logUtils.eob("开始返回onKey.......");
                        if(customWebChromeClient.isVideoFullscreen()){
                            customWebChromeClient.onHideCustomView();
                        }else {
                            wvContent.goBack();
                        }
                        return true;
                    }
                }
                return false;
            }
        });
        wvContent.loadUrl("http://www.kuaiyan.com");
    }
    private UrlAddedListener urlAddedListener = new UrlAddedListener() {
        @Override
        public void beginAdd() {
            logUtils.dob("k開始添加");
        }

        @Override
        public void adding(String url) {
            logUtils.dob("還在添加"+url);
        }

        @Override
        public void addFinished(final List<String> urls) {
            logUtils.dob("添加完成");
            sendUrls(urls);
        }
    };

    private void sendUrls(final List<String> urls) {
        SdkInit.getUiHandle().post(new Runnable() {
            @Override
            public void run() {
                AdFilterBean adFilterBean = new AdFilterBean();
                if(urls==null||urls.size() == 0) {
                    adFilterBean.code = -1;
                    adFilterBean.msg = "获取失败";
                }else{
                    adFilterBean.code = 1;
                    adFilterBean.msg = "获取成功";
                }
                adFilterBean.data = new AdFilterBean.Data();
                adFilterBean.data.interceptUrls = urls;
                adFilterBean.data.url = wvContent.getUrl();
                logUtils.dob("开始发送拦截条目"+ JSON.toJSONString(adFilterBean));
                EventBus.getDefault().post(adFilterBean);
            }
        });
    }

    public void initWebview() {
        View nonVideoLayout = this.findViewById(R.id.nonVideoLayout);
        if(nonVideoLayout instanceof FrameLayout){
            frameLayout = (FrameLayout) nonVideoLayout;
        }
        ViewGroup videoLayout = (ViewGroup)this.findViewById(R.id.rl_content_full);
        View loadingViewVideo = View.inflate(this,R.layout.view_loading_video, null);


        wvContent = ((CustomWebview) this.findViewById(R.id.wv_content));
        errorView = this.findViewById(R.id.in_error);
        loadingView = this.findViewById(R.id.in_loading);
        errorRefresh = (Button) this.findViewById(R.id.bt_error);
        errorRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logUtils.dob("开始刷星");
                wvContent.loadUrl(wvContent.getUrl());
            }
        });
        progressBar = (ProgressBar) loadingView.findViewById(R.id.pb_loading);
        customWebChromeClient = new CustomWebChromeClient(nonVideoLayout,videoLayout,loadingViewVideo, wvContent,this);
        customWebChromeClient.setWebchromClientCallback(new WebchromClientCallback() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if(newProgress >= 90){
                    loadingView.setVisibility(View.GONE);
                } else{
                    loadingView.setVisibility(View.VISIBLE);
                    progressBar.setProgress(newProgress);
                }
            }

            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
            }
        });
        customWebViewClient = new CustomWebViewClient(urlAddedListener){
            @Override
            public void onPageFinished(WebView view, String url) {
                showSucess();
                super.onPageFinished(view, url);
            }
        };
        customWebChromeClient.setOnToggledFullscreen(new ToggledFullscreenCallback()
        {
            @Override
            public void toggledFullscreen(boolean fullscreen)
            {
                // Your code to handle the full-screen change, for example showing and hiding the novel_title bar. Example:
                if (fullscreen)
                {
                    ViewUtils.vedioOrtentionChanged(tintManager,MainActivity.this, ViewUtils.ORTENTION_LAND);
                    wvContent.doOnResume();
                }
                else
                {
                    ViewUtils.vedioOrtentionChanged(tintManager,MainActivity.this,ViewUtils.ORTENTION_PROFIT);
                    wvContent.doOnResume();
                }
            }
        });
        wvContent.setWebChromeClient(customWebChromeClient);
        wvContent.setWebViewClient(customWebViewClient);
    }

    /**
     * 展示成功页面
     */
    public void showSucess(){
        wvContent.setVisibility(View.VISIBLE);
        errorView.setVisibility(View.GONE);
        loadingView.setVisibility(View.GONE);
    }
    /**
     * eventBus 回调
     *
     * @param protocalMsg
     */
    public void onEventMainThread(ProtocalMsg protocalMsg) {
        if (protocalMsg != null ) {
            if(protocalMsg.code == 1) {
                if (wvContent != null) {
                    String data = protocalMsg.data;
                    if(data.contains("?")){
                        data = data+"&time="+System.currentTimeMillis();
                    }else{
                        data = data+"?time="+System.currentTimeMillis();
                    }
                    wvContent.loadUrl(data);
                }
            }else if(protocalMsg.code == 2){
               List<String> urls =  customWebViewClient.getUrls();
               sendUrls(urls);
            }else if(protocalMsg.code == 3){
                customWebViewClient.clearInterceptUrl();
                customWebViewClient.addInterceptUrl(protocalMsg.interCeptUrl);
                if (wvContent != null) {
                   wvContent.reload();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        Intent intent = new Intent(this, SocketService.class);
        stopService(intent);
    }
}
